import { adminLogin } from '@/api/common/login'
import {setLoginUser, removeLoginUser, getAppApiUrl} from '@/utils/auth'
import { logout } from '@/api/common/currentLoginUser'
import { LoginUser } from '@/model/loginUser'
import { querySystemCustomContentJsonByCustomKey } from "@/api/system/systemCustom"
import md5 from 'js-md5'

const user = {
  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const loginName = userInfo.loginName
      const password = md5(userInfo.password)
      const imageCode = userInfo.imageCode
      const imageId = userInfo.imageId
      const loginData = {loginName,password,imageCode,imageId}
      return new Promise((resolve, reject) => {
        adminLogin(loginData).then(res => {
          if (res.errorCode === 0) {
            let user = res.data;
            setLoginUser(new LoginUser(user, getAppApiUrl()))
            resolve(res)
          } else {
            resolve(res)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户风格设置
    GetUserLayoutSetting({ commit, state },store) {
      return new Promise((resolve, reject) => {
        querySystemCustomContentJsonByCustomKey({customKey: "layoutSetting"}).then(custom => {
          if (custom&&custom.data){
            const  layoutSettingData = JSON.parse(JSON.stringify(custom.data));
            //设置缓存
            localStorage.setItem("layout-setting",layoutSettingData);
            //改变风格样式全局常量
            const changeSettingData = JSON.parse(custom.data);
            store.dispatch('settings/changeSetting', {key: 'topNav', value: changeSettingData.topNav})
            store.dispatch('settings/changeSetting', {key: 'tagsView', value: changeSettingData.tagsView})
            store.dispatch('settings/changeSetting', {key: 'fixedHeader',value: changeSettingData.fixedHeader})
            store.dispatch('settings/changeSetting', {key: 'sidebarLogo',value: changeSettingData.sidebarLogo})
            store.dispatch('settings/changeSetting', {key: 'dynamicTitle',value: changeSettingData.dynamicTitle})
            store.dispatch('settings/changeSetting', {key: 'sideTheme',value: changeSettingData.sideTheme})
            store.dispatch('settings/changeSetting', {key: 'theme',value: changeSettingData.theme})
          }
          resolve(custom)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          removeLoginUser()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        removeLoginUser()
        resolve()
      })
    }
  }
}
export default user
